package com.jing.system.comm;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import weibo4j.model.User;
import weibo4j.model.UserWapper;
import weibo4j.model.WeiboException;

import com.jing.system.comm.contants.WeiboCons;
import com.jing.system.comm.enums.FansAttentionType;
import com.jing.system.comm.enums.GenderType;
import com.jing.weibo.pojo.Fansattention;
import com.jing.weibo.pojo.Synchrolog;
import com.jing.weibo.pojo.UserInfo;
import com.jing.weibo.service.fans.FansAttentionService;
import com.jing.weibo.service.user.SynchrologService;
import com.jing.weibo.ws.sina.SinaService;

/**
 * Base Controller
 * @author jing.yue
 * @version 2012/08/29 1.0.0
 */
public class BaseController {

	private static final Logger logger = Logger.getLogger(BaseController.class);
	public static final String SUCCESS = "success";
	public static final String ERROR = "error";
	public static final String ERROR_WEIBO = "error_weibo";
	public static final String ERROR_ISOPENMP = "error_isopenmp";

	@Autowired
	private SynchrologService synchrologService;

	@Autowired
	private SinaService sinaService;

	/*@Autowired
	private TaskManager taskManager;*/

	@Autowired
	private FansAttentionService fansAttentionService;

	public final static String SESSION_USER_KEY = "userInfo";
	public final static String FORCELOGIN = "forcelogin";

	/**
	 * 修改同步记录时间
	 * @param request
	 * @param fansAttentionType
	 * @throws Exception
	 */
	public void updateSynchrologInfo(HttpServletRequest request, FansAttentionType fansAttentionType) throws Exception {
		// TODO Auto-generated method stub
		UserInfo userInfo = getSessionUser(request);
		Synchrolog synchrolog = new Synchrolog();
		synchrolog.setUsername(userInfo.getUsername());
		synchrolog.setSynchrotable(fansAttentionType.getCode());
		Synchrolog sl = synchrologService.findByUserNameSynchrotable(synchrolog);
		//有数据
		if(sl != null) {
			//根据用户名和类型删除记录
			synchrologService.deleteSynchrolog(sl);
			
			//根据用户名和类型删除粉丝等记录
			Fansattention fansattention = new Fansattention();
			fansattention.setUsername(userInfo.getUsername());
			fansattention.setType(fansAttentionType.getCode());
			fansAttentionService.deleteFansattention(fansattention);

			/*//添加定时任务
			String dateStr = DateUtil.dateToString(Calendar.getInstance().getTime(), DateUtil.FMT_DEFAULT);
			taskManager.addTask(dateStr.substring(0, 10), dateStr.substring(11, 13), dateStr.substring(14, 16), dateStr.substring(17, 19), userInfo.getUsername(), userInfo.getToken(), fansAttentionType);*/
		}
	}

	/**
	 * 根据类型同步记录到数据库
	 * @param request
	 * @param synchroType
	 * @throws Exception
	 */
	public void synchrologInfo(HttpServletRequest request, FansAttentionType fansAttentionType) throws Exception {
		// TODO Auto-generated method stub
		UserInfo userInfo = getSessionUser(request);
		
		//判断是否同步过
		Synchrolog synchrolog = new Synchrolog();
		synchrolog.setUsername(userInfo.getUsername());
		synchrolog.setSynchrotable(fansAttentionType.getCode());
		Synchrolog sl = synchrologService.findByUserNameSynchrotable(synchrolog);
		
		Date querytime = DateUtils.addMinutes(Calendar.getInstance().getTime(), WeiboCons.UPDATE_PAST_DUE_DATE);
		//超过时间则从新获取数据[默认为15分钟]
		if(sl != null && sl.getSynchrotime().compareTo(querytime) == -1) {
			updateSynchrologInfo(request, fansAttentionType);
			sl = null;
		}
		//不存在记录
		if(sl == null) {
			sl = new Synchrolog();
			sl.setNextcursor("0");
			String nextcursor = synchroFansAttention(userInfo, fansAttentionType, sl);
			if(nextcursor != null) {
				//添加用户同步记录
				synchrolog.setNextcursor(nextcursor);
				synchrologService.saveSynchrolog(synchrolog);
			}

			/*//添加定时任务
			String dateStr = DateUtil.dateToString(Calendar.getInstance().getTime(), DateUtil.FMT_DEFAULT);
			taskManager.addTask(dateStr.substring(0, 10), dateStr.substring(11, 13), dateStr.substring(14, 16), dateStr.substring(17, 19), userInfo.getUsername(), userInfo.getToken(), fansAttentionType);*/
		}
		//有数据
		else if(sl != null) {
			String nextcursor = synchroFansAttention(userInfo, fansAttentionType, sl);
			if(nextcursor != null) {
				//根据用户名和同步的表名修改用户同步记录信息
				sl.setNextcursor(nextcursor);
				synchrologService.updateSynchrolog(sl);
			}

			/*//添加定时任务
			String dateStr = DateUtil.dateToString(Calendar.getInstance().getTime(), DateUtil.FMT_DEFAULT);
			taskManager.addTask(dateStr.substring(0, 10), dateStr.substring(11, 13), dateStr.substring(14, 16), dateStr.substring(17, 19), userInfo.getUsername(), userInfo.getToken(), fansAttentionType);*/
		}
		/*Date querytime = DateUtils.addMinutes(Calendar.getInstance().getTime(), WeiboCons.UPDATE_PAST_DUE_DATE);
		//不存在记录
		if(sl == null) {
			String nextcursor = synchroFansAttention(userInfo, fansAttentionType, sl);
			if(nextcursor != null) {
				//添加用户同步记录
				synchrolog.setNextcursor(nextcursor);
				synchrologService.saveSynchrolog(synchrolog);
			}

			//添加定时任务
			String dateStr = DateUtil.dateToString(Calendar.getInstance().getTime(), DateUtil.FMT_DEFAULT);
			taskManager.addTask(dateStr.substring(0, 10), dateStr.substring(11, 13), dateStr.substring(14, 16), dateStr.substring(17, 19), userInfo.getUsername(), userInfo.getToken(), fansAttentionType);
		}
		//有数据, 但距离上传更新数据超过15分钟
		else if(isSynchro || (sl != null && sl.getSynchrotime().compareTo(querytime) == -1) ) {
			String nextcursor = synchroFansAttention(userInfo, fansAttentionType, sl);
			if(nextcursor != null) {
				//根据用户名和同步的表名修改用户同步记录信息
				synchrolog.setNextcursor(nextcursor);
				synchrologService.updateSynchrolog(sl);
			}

			//添加定时任务
			String dateStr = DateUtil.dateToString(Calendar.getInstance().getTime(), DateUtil.FMT_DEFAULT);
			taskManager.addTask(dateStr.substring(0, 10), dateStr.substring(11, 13), dateStr.substring(14, 16), dateStr.substring(17, 19), userInfo.getUsername(), userInfo.getToken(), fansAttentionType);
		}*/
	}

	/**
	 * 保存信息
	 * @param username
	 * @param fansAttentionType
	 * @param fansattention
	 * @param userWapper
	 * @throws Exception
	 */
	private void saveFansattention(String username, FansAttentionType fansAttentionType, Fansattention fansattention, UserWapper userWapper) throws Exception {
		// TODO Auto-generated method stub

		for (User user : userWapper.getUsers()) {
			//设置信息
			fansattention = BaseController.setFansattention(user, username, fansAttentionType.getCode());
			//保存粉丝信息
			fansAttentionService.saveFansattention(fansattention);
		}
	}

	/**
	 * 同步粉丝信息
	 * @param userInfo
	 * @param fansAttentionType
	 * @param synchrolog 
	 * @throws WeiboException, Exception
	 */
	private String synchroFansAttention(UserInfo userInfo, FansAttentionType fansAttentionType, Synchrolog synchrolog) throws WeiboException, Exception {
		// TODO Auto-generated method stub
		logger.info(userInfo.getNickname() + ":获取" + fansAttentionType.getText() + "数据!\t cursor: " + synchrolog.getNextcursor());
		//为空或-1则不查询粉丝信息
		if(synchrolog.getNextcursor() == null || "-1".equals(synchrolog.getNextcursor().trim())) {
			logger.info(userInfo.getNickname() + ":已经获取全部" + fansAttentionType.getText() + "完成!");
			return null;
		}
		UserWapper userWapper = null;
		Fansattention fansattention = null;
		switch (fansAttentionType) {
		case TYPE_ATTENTION:
			
			//根据用户和类型删除历史记录
			/*fansattention = new Fansattention();
			fansattention.setUsername(userInfo.getUsername());
			fansattention.setType(fansAttentionType.getCode());
			fansAttentionService.deleteFansattention(fansattention);*/

			//获取所有关注
			//int friendsSize = 0;
			//List<UserWapper> friendsList = sinaService.getFriendsByIDAll(userInfo.getUsername(), userInfo.getToken());
			userWapper = sinaService.getFriendsByID(userInfo.getUsername(), WeiboCons.WEIBO_USER_FANS_ATTENTION_PAGE_SIZE, Integer.valueOf(synchrolog.getNextcursor()), userInfo.getToken());
			//不存在数据
			if(userWapper == null || userWapper.getUsers() == null || userWapper.getUsers().size() == 0) {
				return null;
			}
			//不存在下一页
			else if(userWapper.getNextCursor() <= 0l) {
				saveFansattention(userInfo.getUsername(), fansAttentionType, fansattention, userWapper);
				return "-1";
			}
			saveFansattention(userInfo.getUsername(), fansAttentionType, fansattention, userWapper);
			return Long.toString(userWapper.getNextCursor());

			/*for (UserWapper userWapper : friendsList) {
				for (User user : userWapper.getUsers()) {

					//设置信息
					fansattention = setFansattention(user, userInfo.getUsername(), fansAttentionType.getCode());

					//保存粉丝信息
					fansAttentionService.saveFansattention(fansattention);
				}
				friendsSize += userWapper.getUsers().size();
			}
			logger.info("[" + userInfo.getUsername() + "]关注为: " + friendsSize);
			break;*/
		case TYPE_FANS:

			//获取所有粉丝
			/*int fansSize = 0;
			List<UserWapper> fansList = sinaService.getFollowersByIdAll(userInfo.getUsername(), userInfo.getToken());*/

			
			userWapper = sinaService.getFollowersById(userInfo.getUsername(), WeiboCons.WEIBO_USER_FANS_ATTENTION_PAGE_SIZE, Integer.valueOf(synchrolog.getNextcursor()), userInfo.getToken());
			//不存在数据
			if(userWapper == null || userWapper.getUsers() == null || userWapper.getUsers().size() == 0) {
				return null;
			}
			//不存在下一页
			else if(userWapper.getNextCursor() <= 0l) {
				saveFansattention(userInfo.getUsername(), fansAttentionType, fansattention, userWapper);
				return "-1";
			}
			saveFansattention(userInfo.getUsername(), fansAttentionType, fansattention, userWapper);
			return Long.toString(userWapper.getNextCursor());
			
			
			/*//根据用户和类型删除历史记录
			fansattention = new Fansattention();
			fansattention.setUsername(userInfo.getUsername());
			fansattention.setType(fansAttentionType.getCode());
			fansAttentionService.deleteFansattention(fansattention);
			for (UserWapper userWapper : fansList) {
				for (User user : userWapper.getUsers()) {

					//设置信息
					fansattention = setFansattention(user, userInfo.getUsername(), fansAttentionType.getCode());

					//保存粉丝信息
					fansAttentionService.saveFansattention(fansattention);
				}
				fansSize += userWapper.getUsers().size();
			}
			logger.info("[" + userInfo.getUsername() + "]粉丝为: " + fansSize);
			break;*/
		default:
			break;
		}
		return null;
	}
	/*private void synchroFansAttention(UserInfo userInfo, FansAttentionType fansAttentionType) throws WeiboException, Exception {
		Fansattention fansattention = null;
		switch (fansAttentionType) {
		case TYPE_ATTENTION:

			//获取所有关注
			int friendsSize = 0;
			List<UserWapper> friendsList = sinaService.getFriendsByIDAll(userInfo.getUsername(), userInfo.getToken());

			//根据用户和类型删除历史记录
			fansattention = new Fansattention();
			fansattention.setUsername(userInfo.getUsername());
			fansattention.setType(fansAttentionType.getCode());
			fansAttentionService.deleteFansattention(fansattention);

			for (UserWapper userWapper : friendsList) {
				for (User user : userWapper.getUsers()) {

					//设置信息
					fansattention = setFansattention(user, userInfo.getUsername(), fansAttentionType.getCode());

					//保存粉丝信息
					fansAttentionService.saveFansattention(fansattention);
				}
				friendsSize += userWapper.getUsers().size();
			}
			logger.info("[" + userInfo.getUsername() + "]关注为: " + friendsSize);
			break;
		case TYPE_FANS:

			//获取所有粉丝
			int fansSize = 0;
			List<UserWapper> fansList = sinaService.getFollowersByIdAll(userInfo.getUsername(), userInfo.getToken());

			//根据用户和类型删除历史记录
			fansattention = new Fansattention();
			fansattention.setUsername(userInfo.getUsername());
			fansattention.setType(fansAttentionType.getCode());
			fansAttentionService.deleteFansattention(fansattention);
			for (UserWapper userWapper : fansList) {
				for (User user : userWapper.getUsers()) {

					//设置信息
					fansattention = setFansattention(user, userInfo.getUsername(), fansAttentionType.getCode());

					//保存粉丝信息
					fansAttentionService.saveFansattention(fansattention);
				}
				fansSize += userWapper.getUsers().size();
			}
			logger.info("[" + userInfo.getUsername() + "]粉丝为: " + fansSize);
			break;
		default:
			break;
		}
	}*/

	/**
	 * 设置信息
	 * @param user
	 * @param uid
	 * @param type
	 * @return
	 */
	public static Fansattention setFansattention(User user, String uid, String type) {
		// TODO Auto-generated method stub
		Fansattention fansattention = new Fansattention();
		//用户名
		fansattention.setUsername(uid);
		//粉丝关注的用户名
		fansattention.setFansattentionusername(user.getId());
		//类型[0粉丝/1关注/2互相关注]
		fansattention.setType(type);
		//粉丝关注的昵称
		fansattention.setNickname(user.getScreenName());
		//关注数
		fansattention.setAttentionnum(Integer.toString(user.getFriendsCount()));
		//粉丝数
		fansattention.setFansnum(Integer.toString(user.getFollowersCount()));
		//微博数
		fansattention.setWeibonum(Integer.toString(user.getStatusesCount()));
		//头像
		fansattention.setImg(user.getavatarLarge());
		//性别
		fansattention.setGender(GenderType.getCodeByText(user.getGender()));
		//该用户是否关注当前登录用户
		fansattention.setFollowme(Boolean.toString(user.isFollowMe()));
		//当前登录用户是否关注了该用户
		fansattention.setFollowing(Boolean.toString(user.isFollowing()));
		return fansattention;
	}

	/**
	 * 从Session中获取用户信息
	 * @param request
	 * @return
	 */
	public UserInfo getSessionUser(HttpServletRequest request) {
		// TODO Auto-generated method stub
		return (UserInfo) request.getSession().getAttribute(SESSION_USER_KEY);
	}

	/**
	 * 设置授权了的用户信息到Session中
	 * @param request
	 * @param user
	 */
	public void setSessionUser(HttpServletRequest request, UserInfo user) {
		// TODO Auto-generated method stub
		request.getSession().setAttribute(SESSION_USER_KEY, user);
	}

	/**
	 * 移除授权了的Session中的用户信息
	 * @param request
	 */
	public void removeSessionUser(HttpServletRequest request) {
		// TODO Auto-generated method stub
		request.getSession().removeAttribute(SESSION_USER_KEY);
	}

	/**
	 * 设置值到Session中
	 * @param request
	 * @param key
	 * @param value
	 */
	public void setSession(HttpServletRequest request, String key, String value) {
		request.getSession().setAttribute(key, value);
	}

	/**
	 * 移除Session中的信息
	 * @param request
	 * @param key
	 */
	public void removeSession(HttpServletRequest request, String key) {
		// TODO Auto-generated method stub
		request.getSession().removeAttribute(key);
	}
}